import { getCollection } from '@/service/collection';
import { AddRoleParams, IRole, UpdateRoleParams } from '@/service/types';
import { pick, rest } from 'lodash-es';

export const roleCollection = getCollection<IRole>('uni-id-roles');

const fields = ['role_id', 'role_name', 'comment', 'permission'];

const existRole = async (role_id: string) => {
	try {
		const res = await roleCollection.where({ role_id }).getOne();
		return !!res.data;
	} catch (error) {
		throw error;
	}
};

const existRoleById = async (id: string) => {
	try {
		const res = await roleCollection.where({ _id: id }).getOne();
		return !!res.data;
	} catch (error) {
		throw error;
	}
};
const getAllRole = async () => {
	try {
		const res = await roleCollection.get();
		return res.data;
	} catch (error) {
		throw error;
	}
};

const getRoleTreeOptions = async () => {
	try {
		const res = await roleCollection.getTree();
		return res.data;
	} catch (error) {
		throw error;
	}
};
const getPaginationRole = async (params: PaginationParams) => {
	try {
		const res = await roleCollection
			.where(params.query ? params.query : {})
			.limit(params.limit)
			.skip(params.skip)
			.get({ getCount: true });
		return res;
	} catch (error) {
		throw error;
	}
};
const addRole = async (data: AddRoleParams) => {
	try {
		const exist = await existRole(data.role_id);
		if (exist) {
			throw new Error('权限标识已存在');
		}

		const pickData = pick(data, fields);

		const res = await roleCollection.add(pickData);
		return res.id;
	} catch (error) {
		throw error;
	}
};

const updateRole = async (data: UpdateRoleParams) => {
	const exist = await existRoleById(data._id);
	if (!exist) {
		throw new Error('权限标识不存在');
	}
	const pickData = pick(data, fields);
	try {
		const res = await roleCollection
			.where({
				_id: data._id,
			})
			.update(pickData);
		return res.updated;
	} catch (error) {
		throw error;
	}
};

const deleteRole = async (id: string) => {
	try {
		const res = await roleCollection.where({ _id: id }).remove();
		return res.deleted;
	} catch (error) {
		throw error;
	}
};
export const role = {
	getAllRole,
	addRole,
	updateRole,
	getPaginationRole,
	deleteRole,
	getRoleTreeOptions,
};
